<?php
class AdminModule extends CWebModule
{
    private $_controller;

	private function getAuthRoute()
    {
		return 'admin/auth';
    }

	private function getLoginRoute()
	{
		return 'admin/auth/login';
	}

	private function isAuthRequest()
	{
		return (0 === strpos($this->_controller->route, $this->getAuthRoute()));
	}

	private function authenticate()
    {
		if (
			(!Yii::app()->user->isGuest || $this->isAuthRequest()) &&
			Yii::app()->securedSession->get(WebUser::SECURED_IS_AUTH)
		) {
			return;
		}
		$this->redirectToLigin();
    }

	private function authorization()
	{
		if (! Yii::app()->user->isAdmin()){
			$this->redirectToLigin();
		}
	}

	private function redirectToLigin()
	{
		if (! $this->isAuthRequest()) {
			$this->_controller->redirect(array('/'.$this->getLoginRoute()));
		}
	}

    public function beforeControllerAction($controller,$action)
    {
		if (parent::beforeControllerAction($controller,$action)) {
			$this->_controller = $controller;
			if ($this->isAuthRequest()) {
				$this->_controller->layout = 'application.views.layouts.login';
			} else {
				$this->_controller->layout = 'application.views.layouts.column2';
			}
			$this->authenticate();
			$this->authorization();
			return true;
		} else {
			return false;
		}
    }
}